package com.jp.knowledge;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.fragment.AttentionFragment;
import com.jp.knowledge.fragment.FoundFragment;
import com.jp.knowledge.fragment.KengpongFragment;
import com.jp.knowledge.fragment.MyFragment;
import com.jp.knowledge.fragment.ToutiaoFragment;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.webUtil.JavaScriptInterface;
import com.jp.knowledge.webUtil.X5WebView;
import com.tencent.smtt.sdk.QbSdk;

import java.util.UUID;

/**
 * 主页activity
 */
public class MainActivity extends SlidingActivity implements BottomNavigationBar.OnTabSelectedListener, ResultSubscriber.OnResultListener {

    /**获取token标识 */
    private final  int TOKEN_CODE=1;

    private BottomNavigationBar bottomBar;

    private FrameLayout contentLayout;

    private Fragment[] fragments;

    private X5WebView  webView;


    private int curPostion=0;

    private String HOME_URL = "http://192.168.32.113:3001/headlines";//"http://g.jp580.com/headlines";// "http://192.168.32.113:3001/headlines";//

    private String[] web_module_name=new String[]{"headlines","follow","compete","discover","mine"};// 头条、关注、竞爆、发现、我的  headlines   follow  compete  discover mine

    private Handler  mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ToasUtil.toast(mContext,msg.obj.toString());
        }
    };

    @Override
    protected int getResourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        initX5WebView();
        initItemTab();

//        loadUrl(HOME_URL);
    }


    /**
     * 加载页面
     * @param url
     */
    public void loadUrl(String url){
//        webView.setVisibility(View.VISIBLE);
        webView.loadUrl(url);
    }

    private void initX5WebView(){
        QbSdk.preInit(mContext);
        webView = (X5WebView) findViewById(R.id.web_content);
//        QbSdk.allowThirdPartyAppDownload(true);
        X5WebView.setSmallWebViewEnabled(true);// 开启webview窗口转移功能
        webView.addJavascriptInterface(new JavaScriptInterface(mHandler), "Android");
    }

    public   void getToken(){
        String uuid = UUID.randomUUID().toString();
        long timeStamp = System.currentTimeMillis();
        JsonObject obj = new JsonObject();
        obj.addProperty("uuid",uuid);
        obj.addProperty("timestamp",timeStamp);
        HttpHelper.getInstance(mContext).getToken(obj.toString(),1,this);
    }



    private void initItemTab(){
        contentLayout = (FrameLayout) findViewById(R.id.content);
        bottomBar = (BottomNavigationBar) findViewById(R.id.tabs);
        bottomBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
        bottomBar.setBarBackgroundColor(R.color.white);
        bottomBar.setActiveColor(R.color.top_bg_color);
        bottomBar.setMinimumHeight(12);
        bottomBar.addItem(new BottomNavigationItem(R.mipmap.toutiaomoren, "头条").setInactiveIconResource((R.mipmap.toutiao)))
                .addItem(new BottomNavigationItem(R.mipmap.toutiaoguanzhu, "关注").setInactiveIconResource((R.mipmap.toutiaoguanzhumoren)))
                .addItem(new BottomNavigationItem(R.mipmap.toutiaojingbao, "竞爆").setInactiveIconResource((R.mipmap.toutiaojingbaomoren)))
                .addItem(new BottomNavigationItem(R.mipmap.toutiaofaxian, "发现").setInactiveIconResource((R.mipmap.toutiaofaxianmoren)))
                .addItem(new BottomNavigationItem(R.mipmap.toutiaowode, "我的").setInactiveIconResource((R.mipmap.toutiaowodemoren)))
                .setFirstSelectedPosition(0)
                .initialise();

        initFragments();
        setDefualtFragment();
        bottomBar.setTabSelectedListener(this);
    }

    private void initFragments() {
        int i=0;
        fragments = new Fragment[5];
        fragments[0]=new ToutiaoFragment();
        fragments[1]=new AttentionFragment();
        fragments[2]=new KengpongFragment();
        fragments[3]=new FoundFragment();
        fragments[4]=new MyFragment();

    }

    private void setDefualtFragment() {
        loadUrl(HOME_URL);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.content, fragments[0]);
        transaction.commit();
    }

    @Override
    public void onTabSelected(int position) {
        curPostion=position;
        if (fragments != null&&position==0||position==3) {//这里暂时指定头条加载原生  其他使用webView加载
            if (position < fragments.length) {
                contentLayout.setVisibility(View.VISIBLE);
                webView.setVisibility(View.GONE);
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = fragments[position];
                if(position==0)setToutiao();
                if(position==3)setFound();
                if (fragment.isAdded()) {
//                    ft.replace(R.id.content, fragment);
                    ft.show(fragment);
                } else {
                    ft.add(R.id.content, fragment);
                }
                ft.commitAllowingStateLoss();
            }
        }else if(position>0&&position!=3){
            if(position==4){
                startActivity(new Intent(mContext, LoginActivity.class));
            }else{
                contentLayout.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
                callWeb(position);
            }

        }

    }

    private void setToutiao(){
        topName.setText("头条");
//        topName.setCompoundDrawables(getResources().getDrawable(R.mipmap.toutiaologo),null,null,null);
        topDesc.setText("最有价值的头条");
    }

    /**
     * 设置关注
     */
    private void setAttention(){
        topName.setText("关注");
//        topName.setCompoundDrawables(getResources().getDrawable(R.mipmap.toutiaologo),null,null,null);
        topDesc.setText("时刻关注一切\n");
    }

    /**
     * 设置轻体验
     */
    private void setTiyan(){
        topName.setText("体验");
//        topName.setCompoundDrawables(getResources().getDrawable(R.mipmap.toutiaologo),null,null,null);
        topDesc.setText("免安装的产品体验");
    }

    private void setFound(){
        topName.setText("发现");
//        topName.setCompoundDrawables(getResources().getDrawable(R.mipmap.toutiaologo),null,null,null);
        topDesc.setText("探索互联网世界");
    }
    private  void callWeb(int position){
        webView.loadUrl("javascript:androidBridge.setCurrentPath('"+web_module_name[position]+"')");//设置当前页面路径
        webView.loadUrl("javascript:androidBridge.setInWebView(2)");////设置当前环境，0:H5，1:IOS，2:Android
    }
    @Override
    public void onTabUnselected(int position) {
        if (fragments != null) {
            if (position < fragments.length) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = fragments[position];
//                ft.remove(fragment);
                ft.hide(fragment);
                ft.commitAllowingStateLoss();
            }
        }

    }

    @Override
    public void onTabReselected(int position) {

    }

    @Override
    public void onStart(int requestType) {

    }

    @Override
    public void onCompleted(int requestType) {

    }

    @Override
    public void onError(int requestType) {

    }

    @Override
    public void onNext(IModel t, int requestType) {
        JsonObject  obj = new JsonParser().parse(t.getData().toString()).getAsJsonObject();
        if(requestType==TOKEN_CODE){//获取token
            application.token = obj.get("token").getAsString();
            application.uuid= obj.get("uuid").getAsString();
            initItemTab();
        }
    }

    @Override
    public void onBackPressed() {
            super.onBackPressed();
    }
}
